<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchList">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item>
              <a-input v-model="queryParam.search" placeholder="请输入关键字" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item label="活动时间">
              <a-range-picker style="width: 100%" showToday valueFormat="YYYY-MM-DD" format="YYYY-MM-DD" v-model="queryParam.regTime" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <span :style="{ float: 'left', overflow: 'hidden', marginright: '20px' }">
              <a-button type="primary" @click="searchList">查询</a-button>
              <a-button style="margin-left: 18px" @click="resetList">重置</a-button>
            </span>
          </a-col>
          <a-col :md="4" :sm="6">
            <span :style="{ float: 'right', overflow: 'hidden' }">
              <router-link :to="`/marketingCenter/passenger/detail/add`">
                <a-button type="primary" @click="resetList">新建活动</a-button>
              </router-link>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-tabs default-active-key="" @change="callback" v-model="queryParam.status">
      <a-tab-pane key="" tab="全部"> </a-tab-pane>
      <a-tab-pane key="0" :tab="`未开始(${wait})`"> </a-tab-pane>
      <a-tab-pane key="1" :tab="`进行中(${running})`"> </a-tab-pane>
      <a-tab-pane key="2" tab="已结束"> </a-tab-pane>
    </a-tabs>
    <s-table ref="table" :rowKey="record => record.id" :columns="columns" :data="loadData" :scroll="{ x: 1300 }" :pagination="paginationProps">
      <span slot="status" slot-scope="text, record">
        {{ record.status | statuType }}
      </span>
      <span slot="recommendType" slot-scope="text, record">
        <span>{{ record.recommendType == 0 ? '推荐会员' : '-' }}</span>
      </span>
      <span slot="brandId" slot-scope="text, record">
        {{ record.brandId | brandType }}
      </span>
      <span slot="time" slot-scope="text, record"> {{ record.startTime }} ~ {{ record.endTime }} </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="launch(record.id, record.brandId)">投放</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(record.id)">复制</a>
          <!-- <router-link :to="`/marketingCenter/passenger/detail/${record.id}`"> 复制 </router-link> -->
          <a-divider type="vertical" />
          <router-link :to="`/marketingCenter/passenger/detail/${record.id}`"> 详情 </router-link>
          <a-divider type="vertical" />
          <router-link :to="`/marketingCenter/passenger/information/${record.id}`"> 明细 </router-link>
          <a-divider type="vertical" />
          <a-popconfirm v-if="record.status == 1" title="确定要下架吗?" ok-text="Yes" cancel-text="No" @confirm="confirm(record.id, 1)">
            <a>下架</a>
          </a-popconfirm>
          <a @click="deled(record.id)" v-else>删除</a>
        </template>
      </span>
    </s-table>
    <!-- 推广 -->
    <a-modal v-model="pushVisible" centered @ok="handleOk" title="推广" :width="400">
      <div>推广页面路径：</div>
      <div>
        <span id="copycode"> {{ copyText }} </span>
        <a @click="copy()">点击复制</a>
      </div>
      <div>推广二维码 <a @click="download">下载图片</a></div>
      <img :src="imgUrl" style="width: 200px; height: 200px" />
    </a-modal>
    <!-- 删除 -->
    <a-modal v-model="visible" centered @ok="deleteOk" okText="删除" :width="400">
      <div class="edit-activity">确认要删除该条活动吗？</div>
    </a-modal>
  </a-card>
</template>
<script>
import { politeList, getNumber, politeDetail, politeActivity, operation } from '@/api/marketingCenter/passenger.js'
const columns = [
  {
    title: '编号',
    dataIndex: 'id',
    align: 'center'
  },
  {
    title: '活动名称',
    dataIndex: 'name',
    align: 'center'
  },
  {
    title: '活动时间',
    dataIndex: 'startTime',
    align: 'center',
    scopedSlots: { customRender: 'time' }
  },
  {
    title: '活动状态',
    dataIndex: 'status',
    align: 'center',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '小程序',
    dataIndex: 'brandId',
    align: 'center',
    scopedSlots: { customRender: 'brandId' }
  },
  {
    title: '活动类型',
    dataIndex: 'recommendType',
    align: 'center',
    scopedSlots: { customRender: 'recommendType' }
  },
  {
    title: '推荐人数',
    dataIndex: 'refereesNumber',
    align: 'center'
  },
  {
    title: '被推荐人数',
    dataIndex: 'referralNumber',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '260px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]
import JInput from '@/components/jeecg/JInput'
import { STable, Ellipsis } from '@views/box/components'
import { promote } from '@/api/marketingCenter/passenger'
import { method } from 'lodash'
export default {
  components: {
    JInput,
    STable,
    Ellipsis
  },
  data() {
    return {
      columns,
      launchId: '',
      imgUrl: '',
      copyText: '',
      deleid: '',
      visible: false,
      pushVisible: false,
      wait: '', // 未开始
      running: '', // 进行中
      paginationProps: {
        pageSize: 10,
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
      },
      queryParam: {
        status: '',
        regTime: [],
        search: ''
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this._getNumber()
        const queryParam = JSON.parse(JSON.stringify(this.queryParam))
        const data = {
          ...queryParam,
          current: parameter.pageNo,
          size: parameter.pageSize
        }

        if (queryParam.regTime && queryParam.regTime.length > 0) {
          data.startTime = queryParam.regTime[0]
          data.endTime = queryParam.regTime[1]
        }
        delete data.regTime

        return politeList(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }

            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                pageNo: 0,
                count: 0,
                pageSize: 20
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  filters: {
    statuType(value) {
      if (value == 0) {
        return '未开始'
      } else if (value == 1) {
        return '进行中'
      } else if (value == 2) {
        return '已结束'
      } else if (value == 3) {
        return '已取消'
      }
    },
    brandType(value) {
      if (value == 2738574294) {
        return 'JNBY'
      } else if (value == 2504948039) {
        return '速写CROQUIS'
      } else if (value == 6924108367) {
        return 'Pomme de terre'
      } else if (value == 2822095692) {
        return 'LESS'
      } else if (value == 4) {
        return 'jnby by JNBY'
      } else if (value == 8348044436) {
        return 'JNBYHOME'
      } else if (value == 5) {
        return '江南布衣+'
      } else if (value == 11) {
        return '江南布衣官方Outlet'
      } else if (value == 15) {
        return 'APN73'
      }
    }
  },
  methods: {
    // 投放
    launch(id, brandId) {
      let url = `packages/wm-cloud-jnbyactive/recommend/index?rid=${id}`
      this.copyText = url
      promote(brandId, url).then(res => {
        if (res.code === 200) {
          this.imgUrl = res.data
          this.pushVisible = true
        } else {
          this.$message.error(res.data)
          this.pushVisible = true
        }
      })
    },
    download() {
      const a_link = document.createElement('a')
      fetch(this.imgUrl)
        .then(resLink => resLink.blob())
        .then(blob => {
          a_link.href = URL.createObjectURL(blob)
          console.log(a_link.href)
          a_link.download = '推广二维码'
          document.body.appendChild(a_link)
          a_link.click()
        })
      this.pushVisible = true
    },
    // 删除
    deled(id) {
      this.$confirm({
        title: '确认要删除该条活动吗?',
        onOk: res => {
          return new Promise((resolve, reject) => {
            operation(id, 2)
              .then(res => {
                console.log(res)
                if (res.code == 200) {
                  this.$message.success('删除成功!')
                  this.$refs.table.refresh()
                  resolve()
                } else {
                  this.$message.success(res.msg)
                  reject()
                }
              })
              .catch(err => {
                resolve()
                console.log(err)
              })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() {}
      })
    },
    // 下架
    confirm(id, type) {
      operation(id, type).then(res => {
        if (res.code === 200) {
          this.$message.success('下架成功!')
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.data)
        }
      })
    },
    _getNumber() {
      getNumber().then(res => {
        if (res.code === 200) {
          this.wait = res.data.noStartNumber // 未开始
          this.running = res.data.startNumber // 进行中
        } else {
          this.$message.error(res.data)
        }
      })
    },
    callback() {
      this.$refs.table.refresh()
    },
    copy() {
      const range = document.createRange()
      range.selectNode(document.getElementById('copycode')) //获取复制内容的 id 选择器
      const selection = window.getSelection() //创建 selection对象
      if (selection.rangeCount > 0) selection.removeAllRanges() //如果页面已经有选取了的话，会自动删除这个选区，没有选区的话，会把这个选取加入选区
      selection.addRange(range) //将range对象添加到selection选区当中，会高亮文本块
      document.execCommand('copy') //复制选中的文字到剪贴板
      this.$message.success('复制成功')
      selection.removeRange(range)
    },
    // 搜索
    searchList() {
      this.$refs.table.refresh(true)
    },
    // 重制
    resetList() {
      this.queryParam.regTime = null
      this.queryParam.search = ''
      this.queryParam.status = ''
      this.$refs.table.refresh(true)
    },
    handleOk() {
      this.pushVisible = false
    },
    deleteOk() {
      operation(this.deleid, 2).then(res => {
        if (res.code === 200) {
          this.$message.success('删除成功成功!')
          this.visible = false
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.data)
        }
      })
    },
    // 复制
    handleEdit(id) {
      politeDetail(id).then(res => {
        if (res.code == 200) {
          const data = res.data
          delete data.basis.id
          delete data.share.id
          let params = {
            basis: data.basis,
            rewardList: data.rewardList,
            share: data.share
          }
          console.log(params)
          politeActivity(params).then(res => {
            if (res.code == 200) {
              this.$message.success('复制成功')
              this.$refs.table.refresh(true)
              this.$router.push(`/marketingCenter/passenger/detail/${res.data}`)
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.edit-activity {
  text-align: center;
  margin-top: 24px;
  margin-bottom: 24px;
}
</style>
